package com.dc.chat.app.biz.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dc.chat.app.biz.FriendBiz;
import com.dc.chat.app.biz.UserBiz;
import com.dc.chat.app.service.mp.FriendService;
import com.dc.chat.app.service.mp.UserService;
import com.dc.chat.entity.dao.Friend;
import com.dc.chat.entity.dao.User;
import com.dc.chat.entity.redisCatch.LoginUser;
import com.dc.chat.entity.to.ResponseBean;
import com.dc.chat.entity.to.friend.FriendListItem;
import com.dc.chat.entity.to.friend.SetFriendBackReq;
import com.dc.chat.interceptor.security.SecurityInterceptor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.ws.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FriendBizImpl implements FriendBiz {
    @Resource
    FriendService friendService;
    @Resource
    UserService userService;
    @Resource
    SimpMessagingTemplate simpMessagingTemplate;
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public ResponseBean<List<FriendListItem>> getFriendList() {
        String username = SecurityInterceptor.threadLocal.get();
        User user = userService.selectByUserName(username);
        Integer id = user.getId();
        LambdaQueryWrapper<Friend> wrapper = Wrappers.lambdaQuery(new Friend());
        wrapper.eq(Friend::getUserId,id).orderByDesc(Friend::getCreateTime);
        List<Friend> friends = friendService.getBaseMapper().selectList(wrapper);
        List<FriendListItem> resp=new ArrayList<>();
        for (Friend friend : friends) {
            FriendListItem listItem=new FriendListItem();
            listItem.setUserId(friend.getFriendId());
            listItem.setBack(friend.getBack());
            User myFriend = userService.getById(friend.getFriendId());
            listItem.setUsername(myFriend.getUserName());
            listItem.setNickname(myFriend.getNickName());
            listItem.setAvatar(myFriend.getAvatar());
            listItem.setNoRead(friend.getNoRead());
            Boolean hasKey = redisTemplate.opsForHash().hasKey("login", myFriend.getUserName());
            listItem.setOnline(hasKey);
            resp.add(listItem);
        }
        return ResponseBean.success("查询成功",resp);
    }

    @Override
    @Transactional
    public ResponseBean deleteFriend(Integer friendId) {
        String username = SecurityInterceptor.threadLocal.get();
        User user = userService.selectByUserName(username);
        Integer id = user.getId();
        LambdaQueryWrapper<Friend> friendLambdaQueryWrapper = Wrappers.lambdaQuery(new Friend());
        friendLambdaQueryWrapper.eq(Friend::getFriendId,friendId);
        friendLambdaQueryWrapper.eq(Friend::getUserId,id);
        Friend meToF = friendService.getOne(friendLambdaQueryWrapper);
        boolean remove = friendService.remove(friendLambdaQueryWrapper);
        if(!remove){
            return ResponseBean.failed("你们不是好友");
        }
        friendLambdaQueryWrapper =Wrappers.lambdaQuery(new Friend());
        friendLambdaQueryWrapper.eq(Friend::getFriendId,id);
        friendLambdaQueryWrapper.eq(Friend::getUserId,friendId);
        Friend fTom = friendService.getOne(friendLambdaQueryWrapper);
        friendService.remove(friendLambdaQueryWrapper);
        //websocket 通知
        String userName = user.getUserName();
        User friend = userService.getById(friendId);
        String friendUserName = friend.getUserName();
        Map loginMap = redisTemplate.opsForHash().entries("login");
        String token = (String) loginMap.get(userName);
        Map map=new HashMap();
        map.put("deleteFriend",true);
        map.put("username",friendUserName);
        //查看有没有给他设置备注
        simpMessagingTemplate.convertAndSend("/u/"+token,"删除"+(meToF.getBack()==null?friendUserName:meToF.getBack())+"成功",map);
        String friendToken = (String) loginMap.get(friendUserName);
        Map friendMap=new HashMap();
        friendMap.put("deleteFriend",true);
        friendMap.put("username",username);

        simpMessagingTemplate.convertAndSend("/u/"+friendToken,(fTom.getBack()==null?username:fTom.getBack())+"刚刚删除了你",friendMap);
        return ResponseBean.success("删除成功",null);
    }

    @Override
    public ResponseBean setFriendBack(SetFriendBackReq req) {
        Integer id = req.getId();
        String back = req.getBack();
        String localName = SecurityInterceptor.threadLocal.get();
        User user = userService.selectByUserName(localName);
        boolean check = friendService.check(id, user.getId());
        if(!check){
            return ResponseBean.failed("你俩不是好友");
        }
        LambdaUpdateWrapper<Friend> friendLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        friendLambdaUpdateWrapper.eq(Friend::getUserId,user.getId());
        friendLambdaUpdateWrapper.eq(Friend::getFriendId,id);
        friendLambdaUpdateWrapper.set(Friend::getBack,back);
        boolean update = friendService.update(friendLambdaUpdateWrapper);
        if(update){
            return ResponseBean.success("更新成功",null);
        }else{
            return ResponseBean.failed("更新失败");
        }
    }

    @Override
    public void setActiveUser(Integer id) {
        String username = SecurityInterceptor.threadLocal.get();
        User user = userService.selectByUserName(username);
        LambdaUpdateWrapper<Friend> friendLambdaUpdateWrapper = Wrappers.lambdaUpdate(new Friend());
        friendLambdaUpdateWrapper.eq(Friend::getUserId,user.getId());
        friendLambdaUpdateWrapper.eq(Friend::getFriendId,id);
        friendLambdaUpdateWrapper.set(Friend::getNoRead,0);
        friendService.update(friendLambdaUpdateWrapper);
        Map<String,String> loginTokenMap = redisTemplate.opsForHash().entries("login");
        String token = loginTokenMap.get(username);
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get("login#1#" + username + "#" + token);
        loginUser.setActiveUserId(id);
        loginUser.setActiveGrpId(null);
        redisTemplate.opsForValue().set("login#1#" + username + "#" + token,loginUser);
    }
}
